﻿#region Librerias

using System;
using System.Net;
using ESF.General;
using ESF.General.MVP;
using ESF.SFT.FileUploader.Presenter.FileReceiver;
using System.ServiceModel;
using ESF.SFT.FileUploader.Presenter.FileReceiverGeneral;
using System.ServiceModel.Channels;

#endregion


namespace ESF.SFT.FileUploader.Presenter.General
{
	public class SplashScreenPresenter : BasePresenter<ISplashScreenViewer>
	{
		#region Miembros

		private ReceiverGeneralClient _ReceiverGeneralClient;

		#endregion


		#region Constructor

		public SplashScreenPresenter (ISplashScreenViewer pViewer)
			: base (pViewer) {}

		#endregion


		#region Funciones

		public override void Load ()
		{
			_Viewer.LoadingProgress = 10;
			
			_Viewer.ProductName = ReadConfig.ApplicationName;
			_Viewer.PublisherName = ReadConfig.PublisherName;

			_Viewer.ProductVersion = string.Format ("Versión: {0}", ReadConfig.ExecutingVersion);

		
			ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

			_Viewer.CurrentStep = "Conectando";
			

			_ReceiverGeneralClient = new ReceiverGeneralClient ();

			_Viewer.LoadingProgress = 20;

			PrepareConfiguration ();
			
			_Viewer.CurrentStep = "Iniciando ventanas";

			_Viewer.LoadingProgress = 100;
		}


		private void PrepareConfiguration()
		{
			_Viewer.CurrentStep = "Preparando la Configuración";
			
			try
			{
				using (var scope = new OperationContextScope(_ReceiverGeneralClient.InnerChannel))
				{				 
					OperationContext.Current.OutgoingMessageHeaders.Add (MessageHeader.CreateHeader ("ClientVersion", string.Empty, ReadConfig.ExecutingVersion));

					_Viewer.Conf = _ReceiverGeneralClient.GetConfiguration();
				}
			}
			catch (ProtocolException ptEx)
			{
				if (ptEx.Message.Contains("407"))
				{
					_Viewer.CaptureProxySettings ();

					_Viewer.Conf = _ReceiverGeneralClient.GetConfiguration();
				}
				else
				{
					throw ptEx;
				}
			}
			catch (FaultException fEx)
			{
				LogError (fEx);

				_Viewer.CloseApplication ();
			}
			catch (Exception pEx)
			{
				LogError (pEx);
			}

			_Viewer.LoadingProgress = 50;
		}

		#endregion
	}
}
